// pages/list/list.js

import Dialog from '@vant/weapp/dialog/dialog';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    categories: [
      { id: 1, name: "生活护理", type: "lifeCare" },
      { id: 2, name: "家政服务", type: "householdCleaning" },
      { id: 3, name: "跑腿送货", type: "deliverGoods" },
      { id: 4, name: "其他", type: "others" }
    ],
    // 当前选中的小分类
    showBuy: false,
    currentDate: '12:00',
    minHour: 10,
    maxHour: 20,
    selectedItem: {},
    buttonState: ['plain', 'plain', 'plain'], // 初始化所有按钮为 'plain' 状态
    spec: ['1', "2", '3'],
    selectedOption: 'Option 1', // 默认选中 'Option 1'
    options: [
      { value: 'Option 1', text: '选项 1' },
      { value: 'Option 2', text: '选项 2' },
      { value: 'Option 3', text: '选项 3' }
    ],
    show: false,
    totalPirce:'20',
    Services: [
    ], // 初始化为空数组
    currentServices: [],
    activeKey: '', // 当前激活的分类
    specifications: [],
    cartSpecifications:[],
    cartPrice:'',
    ShoppingCart:[
      
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 初始化时显示所有服务
   this.getAllIn();  // 确保页面加载完成后获取服务数据
 
   this.comSpecs();
   this.comSpecs2();
    this.onCategoryTap2();
   
  },

  /**
   * 获取所有服务数据
   */
  getAllIn() {
    this.backBut();
    wx.request({
      url: 'http://localhost:9001/wx/getAllService', // 注意修改为实际的服务端地址
      method: "GET",
      withCredentials: true, 
      success: (res) => {
        console.log(res);  // 打印接口返回的完整数据
        if (res.data && res.data.data) {
          this.setData({
            Services: res.data.data, // 更新服务数据
            currentServices: res.data.data, // 同时更新当前显示的服务列表
          });
        console.log(1111111);
        this.backBut();
          this.comSpecs();
        }
      },
      fail: (error) => {
        console.error("请求失败:", error);
        console.log(1111111);
        this.comSpecs();
      }
    });
  },

  onCategoryTap: function (e) {
    const categoryId = e.currentTarget.dataset.index; // 获取分类ID
    console.log('点击分类:', categoryId); // 打印分类ID
    const selectedCategory = this.data.categories.find(item => item.id === categoryId);
    console.log('选中的分类:', selectedCategory); // 打印选中的分类信息
    
    if (selectedCategory) {
      this.setData({
        activeKey: selectedCategory.id, // 激活当前分类
        currentServices: this.filterServicesByCategory(selectedCategory.type), // 过滤服务
      });
      console.log(this.data.activeKey);
    }
  },

  onCategoryTap2 () {
  
    const selectedCategory = this.data.categories.find(item => item.id === 1);
    console.log('选中的分类:', selectedCategory); // 打印选中的分类信息
    
    if (selectedCategory) {
      this.setData({
        activeKey: 1, // 激活当前分类
        currentServices: this.filterServicesByCategory(selectedCategory.type), // 过滤服务
      });
      console.log(this.data.activeKey);
    }
  },

  comSpecs() {
    this.data.Services.forEach(service => {
      try {
        // 确保 specificationContent 字符串是有效的 JSON
        service.specificationContent = JSON.parse(service.specificationContent); // 解析并重新赋值
        console.log(service.specificationContent);
      } catch (error) {
        console.error(`Error parsing specificationContent for service ${service.productname}:`, error);
      }
    });
    
    // 更新整个 Services 数据
    this.setData({
      Services: this.data.Services
    });
    console.log(this.data.Services);
  },
  
  comSpecs2() {
    this.data.ShoppingCart.forEach(shopping => {
      try {
        // 确保 specificationContent 字符串是有效的 JSON
        shopping.specification = shopping.specification.split("/"); // 解析并重新赋值
      } catch (error) {
        console.error(`Error parsing specificationContent for service ${service.productname}:`, error);
      }
    });
    
    // 更新整个 Services 数据
    this.setData({
      ShoppingCart: this.data.ShoppingCart
    });
    console.log(33333);
    console.log(this.data.ShoppingCart);
    console.log(111);
    console.log(111);
  },




  filterServicesByCategory: function (categoryType) {
    const filteredServices = this.data.Services.filter(item => item.type === categoryType);
    console.log('过滤后的服务:', filteredServices);
    return filteredServices;
  },

  /**
   * 获取选中的商品信息
   */
  getBuy: function (event) {
   
    const selectedItem = event.currentTarget.dataset.item; // 获取当前点击商品的数据
    console.log(selectedItem);
    wx.setStorage({
      key: 'itemId',  // 存储时的 key
      data: event.currentTarget.dataset.item.id  // 存储的值
    });
    wx.setStorage({
      key:'service',
      data:event.currentTarget.dataset.item
 });

    // 如果 selectedItem 无效，提前返回
    if (!selectedItem) {
      console.error('商品数据无效');
      return;
    }

    this.setData({
      selectedItem: selectedItem,  // 更新选中的商品数据
      showBuy: true  // 显示 van-popup
    });
  },

  /**
   * 关闭弹窗
   */
  onClose() {
    this.setData({ showBuy: false,
      buttonState: ['plain', 'plain', 'plain']
    });

    wx.setStorage({
      key:'service',
      data:null,
    })
    wx.setStorage({
      key:'serviceContent',
      data:null
    })
  },

  onClose1() {
    this.setData({
      show: false
    });
  },

  /**
   * 获取输入框的时间
   */
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },

  /**
   * 点击单选按钮
   */
  onRadioClick: function (event) {
    const selected = event.currentTarget.dataset.value; // 获取当前点击的选项值
    this.setData({
      selectedOption: selected  // 更新选中的选项
    });
  },

  /**
   * 按钮点击事件
   */
  onButtonClick(event) {
    
    const index = event.currentTarget.dataset.index; // 获取点击的按钮的索引
    let newButtonState = ['plain', 'plain', 'plain']; // 重置所有按钮状态为 plain
    newButtonState[index] = 'normal'; // 设置点击的按钮为 normal 状态
    this.setData({
      buttonState: newButtonState // 更新按钮状态
    });


    console.log(event.currentTarget.dataset.item);
    console.log(this.data.Services);
    wx.getStorage({
      key: 'itemId',
      success: (res) => {  // 使用箭头函数来确保 this 的指向
        const id = res.data;
        console.log(id);  // id 为 itemId 的值
        this.data.Services.forEach(service => {  // this 指向正确，能够访问 this.data.Services
          if (service.id === id) {
            console.log(service);
         
            // this.setData({
            //   'this.data.Services.price':
            // })
             wx.setStorage({
              key: 'serviceContent',
              data:event.currentTarget.dataset.item,
             })
            console.log(this.data.Services);
          }
        });
      },
    });
  },

  /**
   * 分组服务项
   */
  groupServices: function () {
    const groupedServices = this.data.Services.reduce((acc, service) => {
      // 如果该分类还没有，初始化该分类
      if (!acc[service.type]) {
        acc[service.type] = [];
      }
      // 将服务添加到对应分类
      acc[service.type].push(service);
      return acc;
    }, {});

    // 转换成需要的数据格式，便于渲染
    const groupedServicesArray = Object.keys(groupedServices).map(type => ({
      type,
      services: groupedServices[type]
    }));

    // 更新 data
    this.setData({
      groupedServices: groupedServicesArray
    });
  },

  addShoppingCart(){
    wx.getStorage({
      key:'service',
      success:(res)=>{
       console.log(res.data);
            wx.getStorage({
              key:'serviceContent',
              success:(res2)=>{
                console.log(res2.data);
              if(res2.data===null){
                
                wx.showToast({
                  title: '请选择规格!!!!!',
                  icon: 'none',
                  duration: 1500
                });                
                }
                else{
                  const specification=`${res.data.productname}/${res2.data.spec_name}/${res2.data.price}`;
                    console.log(specification);
                      wx.request({
                        url: 'http://localhost:9001/wx/addShoppingCart/',
                        method:'POST',
                        data:{
                          "servicename": res.data.productname, 
                          "serviceprice": res2.data.price, 
                          "serviceid": res.data.id, 
                          "picurl": res.data.picUrl,
                          "specification": 
                          specification
                        },
                        success:(res3)=>{
                        
                          console.log(res3.data);  
                          wx.showToast({
                            title: '添加成功',
                            icon: 'none',
                            duration: 1500
                          });
                         
                          this.backBut();
                          this.onClose();
                        }
                      }) 
                }
              }
            })




      }
    })
  },

  getBuy1(){
        wx.request({
          url: 'http://localhost:9001/wx/getShoppingCart',
          method:'GET',
          success:(res)=>{
            this.setData({
              ShoppingCart:res.data.data
            })
            this.comSpecs2();
            const totalPirce2 =this.data.ShoppingCart.reduce((sum, item) => {
              const price = parseFloat(item.specification[2]); // 转换为数字
              return sum + price;
            },0)
            this.setData({
              cartPrice:totalPirce2
            }),
            console.log(totalPirce2);
          }
        })
        this.setData({
          show:true
        })
  },

  deleteCart(event) {
    const { position, instance } = event.detail;
  
    // 手动获取 item 数据
    const item = event.currentTarget.dataset.item || this.cachedItem;
  
    if (!item) {
      console.error('item 未定义，请检查数据绑定');
      return;
    }
    this.cachedItem = item; // 缓存 item，防止数据丢失
    const serviceid = item.serviceid;
  
    switch (position) {
      case 'left':
      case 'cell':
        instance && instance.close();
        break;
      case 'right':
        Dialog.confirm({
          message: '确定删除吗？',
        }).then(() => {
          wx.request({
            url: `http://localhost:9001/wx/deleteShoppingCart/${serviceid}`,
            method: 'GET',
            success: (res) => {
              console.log('删除成功:', res);
              instance && instance.close();
              this.getBuy1();
              this.backBut();
            },
            fail: (err) => {
              console.error('删除失败:', err);
            },
          });
        });
        break;
    }
  },
  
  
  
  cleanCart(){
    Dialog.confirm({
      message: '确定清空清单？',
    }).then(() => {
      console.log(33333);
      wx.request({
        url: 'http://localhost:9001/wx/clearShoppingCart',
        success:(res)=>{
          console.log(res);
          this.getBuy1();
          this.backBut();
          wx.showToast({
           title: res.data.data,
           icon: 'none',
           duration: 1500
         });
        }
      })
    });

  
  },

  subAll(){
    wx.setStorage({
      key:'allCart',
        data:{
         orderdetailList:this.data.ShoppingCart,
         totalPrice:this.data.cartPrice,
         paymentMethod: "支付宝",
        } ,
        success:(res)=>{
          wx.navigateTo({
            url: '/pages/older/older',
            success:(res3)=>{
              console.log(res3);

            }
          })
         
        }
    })


    
   if(this.data.ShoppingCart==null){
    wx.showToast({
      title: '清单为空',
      icon: 'none',
      duration: 1500
    });
   }
   else{
  console.log(this.data.ShoppingCart);
    this.data.ShoppingCart.forEach(ShoppingCart=>{
      //  console.log(ShoppingCart.specification);
         const specification=`${ShoppingCart.specification[0]}/${ShoppingCart.specification[1]}/${ShoppingCart.specification[2]}`;
         console.log(specification);
         ShoppingCart.specification = specification;
    })
    console.log(this.data.ShoppingCart);
    




    wx.request({
      url: 'http://localhost:9001/wx/submitShoppingCart',
      method:'POST',
      data:{
        totalPrice:this.data.cartPrice,
        paymentMethod: "支付宝",
        orderdetailList:this.data.ShoppingCart,
      },
      success:(res2)=>{
         wx.setStorage({
           key:'oriderid',
           data: res2.data.data.orderid
           
         })



              wx.navigateTo({
                url: '/pages/older/older',
                success:(res3)=>{
                  console.log(res3);
                }
              })
             
          
       
      }
    })


   }
    
    
  },

backBut(){
  const categoryId = 1 // 获取分类ID
  console.log('点击分类:', categoryId); // 打印分类ID
  const selectedCategory = this.data.categories.find(item => item.id === categoryId);
  console.log('选中的分类:', selectedCategory); // 打印选中的分类信息
  
  if (selectedCategory) {
    this.setData({
      activeKey: selectedCategory.id, // 激活当前分类
      currentServices: this.filterServicesByCategory(selectedCategory.type), // 过滤服务
    });
    console.log(this.data.activeKey);
  }

},


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 重新获取所有服务
    this.getAllIn();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 这里可以添加分页逻辑或加载更多数据
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    // 分享逻辑
  }
});
